package com.mengfou.appserver;

import android.content.Context;
import android.util.Log;

import com.mengfou.appserver.app.AppGlobalContext;
import com.yanzhenjie.andserver.AndServer;
import com.yanzhenjie.andserver.Server;

import java.util.concurrent.TimeUnit;

/**
 * @author 梦否 on 2024/1/5
 * @blog https://mengfou.blog.csdn.net/
 */
public class ServerManager {

    private static final String TAG = ServerManager.class.getName();

    private Server server;

    public ServerManager(){
        Context applicationContext = AppGlobalContext.instance.getApplicationContext();
        if(applicationContext != null) {
             server = AndServer.webServer(applicationContext)
                    .port(8080)
                    .timeout(10, TimeUnit.SECONDS)
                    .listener(new Server.ServerListener() {
                        @Override
                        public void onStarted() {
                            Log.e(TAG, "onStarted: ");
                        }

                        @Override
                        public void onStopped() {
                            Log.e(TAG, "onStopped: ");
                        }

                        @Override
                        public void onException(Exception e) {
                            Log.e(TAG, "onException: ", e);
                        }
                    })
                    .build();
        }
    }



    public void start() {
        if(server != null) {
            long startTime = System.currentTimeMillis();
            server.startup();
            Log.e(TAG, "startUp costTime: " + (System.currentTimeMillis() - startTime));
        }
    }

    public void stop() {
        if(server != null) {
            server.shutdown();
        }
    }
}
